﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Xml.Linq;

public partial class Submit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StreamReader rd = new StreamReader(Request.InputStream);
        string requestData = rd.ReadToEnd();
        rd.Close();

        if(requestData != null)
            parseXML(requestData);
    }

    public void parseXML(string xmldata)
    {
        XElement details = XElement.Parse(xmldata);
        string deviceID = details.Attribute("DeviceID").Value;
        string emailAddress = details.Element("Email").Value;
        string imageName = details.Element("ImageName").Value;
        string userText = details.Element("UserText").Value;
        float latValue = Convert.ToSingle(details.Element("Latitude").Value);
        float longValue = Convert.ToSingle(details.Element("Longitude").Value);
        string ImageString = details.Element("ImageString").Value;
        byte[] imageBytes = Convert.FromBase64String(ImageString);
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

        System.Drawing.Image dImage = System.Drawing.Image.FromStream(ms, true);
        string hostPath = Server.MapPath("~");
        dImage.Save(hostPath + @"\images\UploadImage\" + imageName, System.Drawing.Imaging.ImageFormat.Jpeg);

        SaveToDB(deviceID, emailAddress, imageName, userText.TrimEnd(), latValue, longValue);

    }

    public void SaveToDB(string deviceID, string emailAddress, string imageName, string userText, float latValue, float longValue)
    {
        WBDataClassesDataContext db = new WBDataClassesDataContext();
        int userID;

        var BBusers = from u in db.WEB_USERs
                      where u.Email == emailAddress
                      select new
                      {
                          u.ID
                      };

        if (BBusers.Count() < 1)
        {
            WEB_USER newUser = new WEB_USER();
            newUser.Email = emailAddress;
            newUser.UserTypeID = 2;
            db.WEB_USERs.InsertOnSubmit(newUser);

            db.SubmitChanges();

            userID = newUser.ID;
        }
        else
            userID = BBusers.First().ID;

        BB_UPLOAD_DATA newPhoto = new BB_UPLOAD_DATA();
        newPhoto.DeviceID = deviceID;
        newPhoto.ImageName = @"images/UploadImage/" + imageName;
        newPhoto.UserText = userText;
        newPhoto.UserID = userID;
        newPhoto.Latitude = latValue;
        newPhoto.Longitude = longValue;
        newPhoto.Email = emailAddress;

        db.BB_UPLOAD_DATAs.InsertOnSubmit(newPhoto);
        db.SubmitChanges();
    }

}

